package com.hongchen.wechat.controller;

import com.hongchen.model.ActGame;
import com.hongchen.model.ActGamePrize;
import com.hongchen.model.ActPrize;
import com.hongchen.model.ActUser;
import com.hongchen.wechat.config.Api;
import com.hongchen.wechat.service.RichService;
import com.jfinal.weixin.sdk.api.ApiResult;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by 任文旭 on 2018/1/16.
 * 介绍: 大富翁掷骰子主方法，其余的游戏都是依托这个游戏进行开发
 * <p>
 * 1、这里用了几种方式去获取openid,当session中获取不到
 * 去全局变量中获取，当全局变量获取不到，去前台拿的
 * userid去用户表中重新查询用户的id去获取openid
 * <p>
 * 2、在掷骰子游戏中，因为当页面加载的时候需要记录上次的步数，当
 * 骰子的数值进行相加的时候移出上次的背景，所以需要进行在显示的时候始终
 * 是数据库中的数据减去 1  这样才能保证下一步移动的时候移出上次的小人
 */
public class RichController extends Api {
    private final RichService richService = enhance(RichService.class);
    static String openId;//定义全局变量的openId

    /***
     * 这是大富翁的进入页面
     * 这里需要的操作就是给用户初始化并且
     * 给用户表存储初始数据
     * */
    public void index() {
        //这里定义一个对象为了更好的获取用户的个人信息
        ApiResult info = userdetail();
        System.out.println(info);
        String openid = info.get("openid");
        openId = info.get("openid");
        setSessionAttr("openid", openid);
        String nickname = info.get("nickname");
        String shuju=getPara("shuju");
        if(shuju==null){
            System.out.println("第一次进入");
        }else {
            setSessionAttr("shuju",shuju);
        }
        /**
         * 判断用户刷新以后openid是否为空
         * 如果为空的话重新拉去用户信息
         *
         */
        if (openid == null) {
            this.redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId()+"&redirect_uri=http://"+chengDong()+".tunnel.echomod.cn/wxcs&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect");
        } else {
            /**
             *  这里还要查询数据库中是否已经存在这个用户，如果已经存在opneid
             *  如果 存在就直接跳转不存在就说明表用户是新用户存贮用户的信息
             */
            ActUser act = richService.findByOpenid(openid);
            if (act == null) {
                //存储用户信息
                ActUser actUser = new ActUser();
                actUser.setCreateTime(new Date());
                actUser.setHeadImg((String) info.get("headimgurl"));
                actUser.setWechatOpenid(openid);
                actUser.setWechatNickname(nickname);
                actUser.setSex((Integer) info.get("sex"));
                actUser.setCity((String) info.get("city"));
                actUser.save();
                ActGame actGame = new ActGame();
                actGame.setActUserId(actUser.getId());
                actGame.setSieveChance((long) 5);
                actGame.setNowTime(new Date());
                actGame.setRedNumber(0);
                actGame.save();
            }
            ActUser num = richService.findnum();
            ActGame actGame = richService.findSignIn(openid);
            setAttr("chance", actGame.getSieveChance());
            setAttr("prev", actGame.getNowStep());
            setAttr("num", num);
            //用户参数
            setAttr("openid", openid);
            setAttr("userId", act.getId());
            setAttr("shuju",getSessionAttr("shuju"));
            render("index.html");
        }
    }

    /**
     * 我的奖品页面显示
     * 打算使用用户的openid进行查询用户的奖品进行遍历
     */
    public void myPrize() {
        String openid = getSessionAttr("openid");
        //如果session中的openidweinull
        if (openid == null) {
            openid = openId;
            if (openid == null) {
                Long userId = getParaToLong("userId");
                ActUser actUser = richService.findUser(userId);
                openid = actUser.getWechatOpenid();
            }
        }
        List<ActGamePrize> actGamePrizes = richService.myPrize(openid);
        setAttr("li", actGamePrizes);
        render("myprize.html");
    }

    /**
     * 跳转到攻略页面
     */
    public void strategy() {
        render("strategy.html");
    }

    /*当点击打卡的时候查询上次打卡的次数*/
    public void findSignIn() {
        String openid = getSessionAttr("openid");
        if (openid == null) {
            openid = openId;
            if (openid == null) {
                Long userId = getParaToLong("userId");
                ActUser actUser = richService.findUser(userId);
                openid = actUser.getWechatOpenid();
            }
        }
        ActGame actGame = richService.findSignIn(openid);
        setAttr("status", actGame.getStatus());
        setAttr("signNu", actGame.getSignNum());
        renderJson();

    }

    /**
     * 签到打卡
     */
    public void signin() {
        //首先根据openid判断在数据库中的签到次数是否为null
        String openid = getSessionAttr("openid");
        if (openid == null) {
            openid = openId;
            if (openid == null) {
                Long userId = getParaToLong("userId");
                ActUser actUser = richService.findUser(userId);
                openid = actUser.getWechatOpenid();
            }
        }

        /**
         * 根据openid判断数据库中游戏表中的状态，当为0的时候允许签到，当
         * 状态为1的时候表示已经签到过了，签到失败
         */
        ActGame actGame = richService.findSignIn(openid);
        if (actGame.getSignNum() == 31) {
            setAttr("result", false);
        } else {
            if (actGame.getStatus() == 0) {
                richService.addOneSign(openid);
                actGame.setStatus(1);//当前签到一次以后。把状态修改为1
                actGame.setSignTime(new Date());
                actGame.update();
            } else {
                setAttr("result", false);
            }
        }
        renderJson();
    }

    /**
     * 用户签到打卡的方法其中
     * （当用户的打卡到7次的时候，用户可以获取2次掷骰子机会以及全勤礼包一份）
     * （15）
     * （30）
     * （31）
     */
    public void signHello() {
        Integer cishu = getParaToInt("cishu");//判断用户签到打卡了几次
        ActGamePrize actGamePrize = new ActGamePrize();
        String openid = getSessionAttr("openid");
        /**这里用了几种方式去获取openid,当session中获取不到
         * 去全局变量中获取，当全局变量获取不到，去前台拿的
         * userid去用户表中重新查询用户的id去获取openid
         */
        if (openid == null) {
            openid = openId;
            if (openid == null) {
                Long userId = getParaToLong("userId");
                ActUser actUser = richService.findUser(userId);
                openid = actUser.getWechatOpenid();
            }
        }
        String no = richService.lastPrizeNo();
        if(no==null){
            Double a = Math.random() * 1000000;
            int b = 1 + (int) (a + 1);
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            no = "MU"+format.format(new Date()) + b;
        }
        ActUser actUser = richService.findByOpenid(openid);
        ActGame actGame = richService.findActId(openid);
        actGamePrize.setGameId(actGame.getId());//游戏表id
        if (cishu == 7) {
            actGamePrize.setPrizeId((long) 22);//奖品表id
            richService.updateSieveChanceTwo(actUser.getId());
        } else if (cishu == 15) {
            actGamePrize.setPrizeId((long) 23);//奖品表id
            richService.updateSieveChanceFour(actUser.getId());
        } else if (cishu == 30) {
            actGamePrize.setPrizeId((long) 24);//奖品表id
            richService.updateSieveChanceSix(actUser.getId());
        } else if (cishu == 31) {
            actGamePrize.setPrizeId((long) 24);//奖品表id
            richService.updateSieveChanceSix(actUser.getId());
        }
        actGamePrize.setPrizeNum(no);//中奖编号
        actGamePrize.setIsRecive(0);
        actGamePrize.setAwardTime(new Date());
        actGamePrize.setAcceptTime(new Date());
        actGamePrize.setAcceptAddres("中国");
        actGamePrize.save();
        setAttr("no", no);
        renderJson();
    }

    public void diceProbability() {
        double a = Math.random();
        int b = 1 + (int) (a * 6);
        setAttr("b", b);
        renderJson();
    }


    /**
     * 开始主游戏，掷骰子
     * 当点击骰子的时候,相应的掷骰子次数也减一
     * 因为需要进行下一步的时候需要移除上次的小人影子，
     * 所以数据库中的数据永远比页面的步数大1
     * 本身92步的路程需要93步来处理，以及所有的奖品以及游戏跳转呀、都需要
     * 减去1
     */
    public void dice() {
        String openid = getSessionAttr("openid");
        int dicenum = getParaToInt("dicenum");
        if (openid == null) {
            Long userId = getParaToLong("userId");
            ActUser actUser = richService.findUser(userId);
            openid = actUser.getWechatOpenid();
        }
        //前台点击骰子的时候，数据库中的机会相应的减一
        ActUser actUser = richService.findByOpenid(openid);
        richService.lessSieveChance(actUser.getId());

        /*记步当前的步数，把掷骰子的步数传过来，给数据库中原有的步数操作
         * c操作之前先查询数据库中的原本步数，如果大于92就在相加以后减去92
         */
        ActGame actGame = richService.finds(actUser.getId());
        if (actGame.getNowStep() + dicenum >= 93) {
            //相加减去92
            richService.lessSteapo( actUser.getId());
        } else {
            richService.updateSteap(dicenum, actUser.getId());
        }
        renderJson();
    }


    /**
     * 陪你晒郑州的方法,同样以奖品的方式进行展示
     * 并且会在集卡那里进行展示，当点击集卡的时候数据库
     * 中查询并且筛选奖品id为【陪你晒郑州的id进行
     * 筛选出来进行各个的展示
     */
    public void showZhengzhou() {
        int st = getParaToInt("steps");
        ActGamePrize actGamePrize = new ActGamePrize();
        String openid = getSessionAttr("openid");
        /**这里用了几种方式去获取openid,当session中获取不到
         * 去全局变量中获取，当全局变量获取不到，去前台拿的
         * userid去用户表中重新查询用户的id去获取openid
         */
        if (openid == null) {
            openid = openId;
            if (openid == null) {
                Long userId = getParaToLong("userId");
                ActUser actUser = richService.findUser(userId);
                openid = actUser.getWechatOpenid();
            }
        }
        String no = richService.lastPrizeNo();
        if(no==null){
            Double a = Math.random() * 1000000;
            int b = 1 + (int) (a + 1);
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            no = "MU"+format.format(new Date()) + b;
        }
        ActUser actUser = richService.findByOpenid(openid);
        ActGame actGame = richService.findActId(openid);
        actGamePrize.setGameId(actGame.getId());//游戏表id
        if (st == 2) {
            actGamePrize.setPrizeId((long) 1);//奖品表id
        } else if (st == 16) {
            actGamePrize.setPrizeId((long) 2);//奖品表id
        } else if (st == 29) {
            actGamePrize.setPrizeId((long) 3);//奖品表id
        } else if (st == 54) {
            actGamePrize.setPrizeId((long) 4);//奖品表id
        } else if (st == 70) {
            actGamePrize.setPrizeId((long) 5);//奖品表id
        }
        actGamePrize.setPrizeNum(no);//中奖编号
        actGamePrize.setIsRecive(0);
        actGamePrize.setAwardTime(new Date());
        actGamePrize.setAcceptTime(new Date());
        actGamePrize.setAcceptAddres("中国");
        actGamePrize.save();
        setAttr("no", no);
        renderJson();
    }


    /**
     * 点击全民集卡按钮的时候,需要查看用户的集卡情况
     */
    public void collectCard() {
        ActGamePrize actGamePrize = new ActGamePrize();
        String openid = getSessionAttr("openid");
        if (openid == null) {
            openid = openId;
            if (openid == null) {
                Long userId = getParaToLong("userId");
                ActUser actUser = richService.findUser(userId);
                openid = actUser.getWechatOpenid();
            }
        }
        List<ActGamePrize> actGamePrizes = richService.coolect(openid);
        setAttr("lis", actGamePrizes);
        renderJson();
    }

    /**
     * 用户兑换陪你晒郑州的方法,主要使用的集合判断
     * 如果数据库中的奖品编码全部包含12345这几个值，就直接进行
     * 接下来的操做，
     */
    public void exchange() {
        String openid = getSessionAttr("openid");
        ActUser actUser = richService.findByOpenid(openid);
        if (openid == null) {
            openid = openId;
            if (openid == null) {
                Long userId = getParaToLong("userId");
                //ActUser actUser = richService.findUser(userId);
                openid = actUser.getWechatOpenid();
            }
        }
        /*兑换,需要把用户的集卡中的陪你晒郑州的卡片的是否领奖的0修改为1
        * 但是之前要判断用户是否全部集齐了陪你晒郑州几张卡片
        * */
        List<ActGamePrize> acList = richService.coolect(openid);
        List<Object> lists = new ArrayList<Object>();
        for (ActGamePrize x : acList) {
            lists.add(x.getPrizeId());
        }
        List<Long> list2 = new ArrayList<Long>();
        list2.add(1l);
        list2.add(2l);
        list2.add(3l);
        list2.add(4l);
        list2.add(5l);
        if (lists.containsAll(list2)) {//表示可以兑换
            //把数据库中的是否领奖的状态修改为1，并且把掷骰子机会增加一
            richService.updateIsRecive(openid);
            //增加掷骰子机会加一
           richService.updateSieveChance(actUser.getId());
            setAttr("res", 1);
        } else {//表示不可以兑换
            setAttr("res", 2);
        }
        renderJson();
    }

    /**
     * 抢到红包存入红包金额，红包次数，抢红包状态
     */
    public void redPacket(){
        String ran = getPara("random");
        double random = Double.parseDouble(ran);
        ActUser actuser=richService.findByOpenid(openId);
        Long  userId=actuser.getId();
        ActGame actg = richService.finds(userId);
        List<ActPrize> apList = richService.typePrize(7);//查询奖品集合
        ActPrize actPrize = richService.isPrize(apList);//奖品
        if(actg != null){
            actg.setNowTime(new Date());
            actg.update();//更新游戏时间
            int num = actg.getRedNumber();
            if(num<3){
                ActGamePrize agp = new ActGamePrize();
                if(random > 2 && random < 7){
                    richService.updateRedNumber(userId);
                    agp.setGameId(actg.getId());
                    agp.setPrizeId(actPrize.getId());
                    agp.setRedMoney(1);
                    agp.setPrizeNum(richService.lastPrizeNo());
                    agp.setAwardTime(new Date());
                    agp.save();
                }else{
                    richService.updateRedNumber(userId);
                    agp.setGameId(actg.getId());
                    agp.setPrizeId(actPrize.getId());
                    agp.setRedMoney(2);
                    agp.setPrizeNum(richService.lastPrizeNo());
                    agp.setAwardTime(new Date());
                    agp.save();
                }
                setAttr("n",num);
            }else{
                setAttr("n",num);
            }

        }renderJson();
    }
      public void redData() {
          String date = getPara("date");
          if (date.equals("0:59:55") || date.equals("1:59:55") || date.equals("2:59:55") || date.equals("3:59:55") || date.equals("4:59:55")|| date.equals("5:59:55")
                  || date.equals("6:59:55")|| date.equals("7:59:55")|| date.equals("8:59:55")|| date.equals("9:59:55")|| date.equals("10:59:55")|| date.equals("11:59:55")
                  || date.equals("12:59:55")|| date.equals("13:59:55")|| date.equals("14:59:55")|| date.equals("15:59:55")|| date.equals("16:59:55")|| date.equals("17:59:55")
                  || date.equals("18:59:55")|| date.equals("19:59:55")|| date.equals("20:59:55")|| date.equals("21:59:55")|| date.equals("22:59:55")|| date.equals("23:59:55")) {
              setAttr("da", 1);
          }
          renderJson();
      }
}































